<?php

namespace App\Http\Controllers\Api;

use App\Handlers\ImageUploadHandler;
use App\Http\Requests\Api\RentClothPostLineRequest;
use App\Http\Requests\Api\RentClothPostRequest;
use App\Http\Requests\Api\PayTypeRequest;
use App\Events\SendNoticeToOne;
use App\Models\Brand;
use App\Models\Commodity;
use App\Models\CommodityAttr;
use App\Models\CommodityType;
use App\Models\DealLine;
use App\Models\DealLog;
use App\Models\EDealLog;
use App\Models\OrderPraise;
use App\Models\PowerLog;
use App\Models\RentCloth;
use App\Models\Recharge;
use App\Models\RentClothDetail;
use App\Models\RentClothOrder;
use App\Models\Shop;
use App\Models\ShopCom;
use App\Models\User;
use App\Models\UserRobe;
use App\Models\Wallet;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;


/**
 * @title 租衣晒单
 * @description 接口说明
 *
 */

class RentClothController extends ApiController
{
    /**
     * @title 商家首页
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/shop_index
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 租衣模块
     *
     * @param name:shop_id type:int require:1 default: other: desc:商铺ID
     * @return shop_name:店铺名称
     * @return stock:库存
     * @return has_bro:借出
     * @return total_member:会员数
     * @return total_power:算力
     * @return total_e:E格码
     * @return total_browse:浏览量
     */
    public function shop_index(Request $request)
    {
        $user = $request->user;
        $shop_id = $request->shop_id;
        $shop_detail = Shop::where('id', $shop_id)->first();
        if (!$shop_detail) {
            return $this->failed('参数错误');
        }
        $shop_browser_num = RentClothOrder::where(['shop_id' => $shop_id, 'status' => 2])->sum('browse_num');
        $info = [];
        $info['shop_name'] = $shop_detail->shop_name;
        $info['stock'] = ShopCom::where(['shop_id' => $shop_id])->sum('stock');
        $bro_count = 0;
        $rent_cloth = RentCloth::where('shop_id', $shop_id)->with('rentclothdetail')->get();
        foreach ($rent_cloth as $value) {
            $bro_count = $bro_count + count($value->rentclothdetail);
        }

        $info['has_bro'] = $bro_count;

        $user_arr = User::where('shop_id', $shop_id)->get()->pluck('id');
        $info['total_member'] = count($user_arr);

        $info['total_power'] = Wallet::whereIn('user_id', $user_arr)->sum('computing_power');
        $info['total_e'] = Wallet::whereIn('user_id', $user_arr)->sum('tmc');
        $info['total_browse'] = $shop_browser_num;

        return $this->success($info);

    }

    /**
     * @title 借衣页面
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/rentClothes
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 租衣模块
     *
     * @return status:借衣状态 0无借衣1已借衣
     */
    public function rentClothes(Request $request, RentCloth $rentcloth)
    {
        $user = $request->user;
        $rentcloth = $rentcloth->where([
            ['user_id', $user->id],
            ['status', 1],
        ])->get();
        if (count($rentcloth) > 0) {
            $status = 1;
        } else {
            $status = 0;
        }
        return $this->success(compact('status'));
    }
    /**
     * @title 借衣编号搜索
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/search_cloth
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 租衣模块
     *
     * @param name:pick_code type:string require:1 default: other: desc:衣服编码
     * @param name:shop_id type:int require:1 default: other: desc:店铺id
     * @return brand_name:品牌名称
     * @return commodity_type:类型
     * @return stock_num:库存
     * @return attr_value:尺码
     * @return commodity_id:衣服ID
     * @return commodity_img:衣服图片
     * @return rent_user_avatar:头像
     * @return rent_num:被借次数
     * @return attr_id:衣服属性ID
     * @return power_price:算力价格
     */
    public function search_cloth(Request $request, CommodityAttr $attr)
    {
        $pick_code = $request->pick_code;
        $shop_id = $request->shop_id;

        if (!$pick_code || !$shop_id) {
            return $this->failed('缺少参数');
        }

        $attr_list = $attr->where('pick_code', $pick_code)->with(['commodity', 'brand', 'commodityType'])->first();
        if (!$attr_list) {
            return $this->failed('没有该商品信息');
        }
        $shop_attr = ShopCom::where(['shop_id' => $shop_id, 'commodity_attr_id' => $attr_list->id, 'is_buy' => 0])->first();
        if (!$shop_attr) {
            return $this->failed('店铺没有该商品');
        }
        if ($shop_attr->is_buy == 1) {
            return $this->failed('该商品不支持租借');
        }

        $data = [];
        $data['brand_name'] = Brand::where('id', $attr_list->commodity->brand_id)->value('name');

        $data['commodity_type'] = CommodityType::where('id', $attr_list->commodity->commodity_type)->value('name');
        $data['stock_num'] = $attr_list->stock_num;
        $data['attr_value'] = $attr_list->attr_value;
        $data['commodity_id'] = $attr_list->commodity_id;
        $data['commodity_img'] = config('app.img_url') . ($attr_list->commodity->pictures)[0];

        $rent_user_avatar = RentClothDetail::where('commodity_attr_id', $attr_list->id)->get()->pluck('user_id');

        $avatar = User::whereIn('id', $rent_user_avatar)->get()->transform(function ($item) {
            $item->user_id = $item->id;
            // $item->avatar = config('app.img_url').$item->avatar;
            return $item->only(['user_id', 'avatar']);
        });

        $data['rent_user_avatar'] = $avatar;
        $data['rent_num'] = RentClothDetail::where('commodity_attr_id', $attr_list->id)->count();
        $data['attr_id'] = $attr_list->id;
        $data['power_price'] = $attr_list->commodity->power_price;

        return $this->success($data);
    }
    /**
     * @title 确认借出页面
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/confirm_rent_cloth
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 租衣模块
     *
     * @param  name:pick_code type:string require:1 default: other: desc:用户输入的编号(如[1,2,3])
     */
    public function confirm_rent_cloth(Request $request, CommodityAttr $attr)
    {
        if (!$request->pick_code) {
            return $this->failed('缺少参数pick_code');
        }
        if (!is_array(json_decode($request->pick_code))) {
            return $this->failed('参数格式错误');
        }
        $pick_code = json_decode($request->pick_code);

        $attr_lists = $attr->whereIn('pick_code', $pick_code)->with(['commodity', 'brand', 'commodityType'])->get();
        if (count($attr_lists) == 0) {
            return $this->failed('没有商品信息');
        }

        $attr_lists->transform(function ($attr_list) {
            $attr_list->brand_name = Brand::where('id', $attr_list->commodity->brand_id)->value('name');
            $attr_list->commodity_img = config('app.img_url') . ($attr_list->commodity->pictures)[0];
            $attr_list->commodity_type = CommodityType::where('id', $attr_list->commodity->commodity_type)->value('name');
            $attr_list->stock_num = $attr_list->stock_num;
            $attr_list->attr_value = $attr_list->attr_value;
            $attr_list->attr_id = $attr_list->id;
            $attr_list->power_price = $attr_list->commodity->power_price;
            return $attr_list->only(['brand_name', 'commodity_img', 'commodity_type', 'stock_num', 'attr_value', 'attr_id', 'power_price']);
        });
        $total_price = $attr_lists->sum('power_price');
        return $this->success(compact('attr_lists', 'total_price'));
    }
    /**
     * @title 确认借出按钮
     * @description 接口说明 total_price=50
     * @author wjx
     * @url /api/rentcloth/confirm_rent_cloth_button
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 租衣模块
     *
     * @param  name:attr_id type:string require:1 default: other: desc:衣服编号ID(如[1,2,3])
     * @param  name:shop_id type:int require:1 default: other: desc:店铺id
     * @param  name:addr_id type:int require: default: other: desc:线上需要传收货地址
     */
    public function confirm_rent_cloth_button(Request $request, CommodityAttr $attr, RentCloth $rentcloth)
    {
        $user = $request->user;
        $shop_id = $request->shop_id;
        $rent_num = $rentcloth->where([['user_id', $user->id], ['type', '<>', 3], ['status', '<>', 2]])->first();
        if ($rent_num && $rent_num->type == 1) {
            return $this->failed('线上已有借衣订单,请归还后再借');
        }
        if ($rent_num) {
            return $this->failed('已有借衣订单,请归还后再借');
        }

        $attr_id = json_decode($request->attr_id);

        if (!is_array($attr_id)) {
            return $this->failed('attr_id参数错误');
        }
        if (count($attr_id) > $user->robe_num) {
            return $this->failed('超出租衣数量');
        }

        $total_price = 50;

        if (!$attr_id || !$total_price || !$shop_id) {
            return $this->failed('缺少参数');
        }
        $type = Shop::where('id', $shop_id)->value('shop_type');
        $user_power = $user->wallet->computing_power;
        if ($user_power < $total_price) {
            return $this->failed('算力不足，请充值');
        }
        $new_power = bcsub($user_power, $total_price, 2);

        $attr_datas = ShopCom::whereIn('commodity_attr_id', $attr_id)->where(['shop_id' => $shop_id, 'is_buy' => 0])->get();

        if (count($attr_datas) == 0) {
            return $this->failed('没有该商品');
        }
        foreach ($attr_datas as $value) {
            if ($value->stock == 0) {
                return $this->failed('库存不足');
            }
        }

        switch ($type) {
            case '1':
                $rent_time = 0;
                $status = 3;
                $addr_id = $request->addr_id;
                if (!$addr_id) {
                    return $this->failed('请选择收货地址');
                }
                break;
            case '2':
                $rent_time = time();
                $status = 1;
                $addr_id = 0;

                break;
            default:
                break;
        }

        $rent_data = [
            'user_id' => $user->id,
            'shop_id' => $shop_id,
            'type' => $type,
            'rent_time' => $rent_time,
            'addr_id' => $addr_id,
            'status' => $status,
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ];

        DB::beginTransaction();
        try {
            if ($type == 1) { //清空借衣衣柜
                UserRobe::where(['user_id' => $user->id, 'type' => 0])->delete();
            }
            if($user->robe_num == 3){
                $user->robe_num = 2;
                $user->save();
            }
            $rent_id = RentCloth::insertGetId($rent_data);

            foreach ($attr_datas as $key => $value) {
                RentClothDetail::insert([
                    'rent_id' => $rent_id,
                    'user_id' => $user->id,
                    'commodity_id' => $value->commodity_id,
                    'commodity_attr_id' => $value->commodity_attr_id,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ]);
                ShopCom::where(['shop_id' => $value->shop_id, 'commodity_attr_id' => $value->commodity_attr_id, 'is_buy' => 0])->decrement('stock', 1); //目前每件衣服只能借一件
            }

            Wallet::where('user_id', $user->id)->update([
                'computing_power' => $new_power,
            ]);
            PowerLog::add_log($user->id, 3, $total_price, 2);
            DB::commit();
            return $this->message('租衣成功');
        } catch (\Exception $exception) {
            DB::rollBack();

            return $this->failed('租衣失败');
        }

    }

    /**
     * @title 添加租衣晒单
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/add_rentcloth_post
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 晒单模块
     * @param name:rent_id type:int require:1  other: desc:租衣记录id
     * @param name:content type:string require:1  other: desc:评论
     * @param name:post_img type:string require:1 other: desc:图片(格式：["1","2","3"])
     *
     */
    public function add_rentcloth_post(Request $request, RentClothPostRequest $postRequest, RentClothOrder $order, ImageUploadHandler $uploader)
    {
        $user = $request->user;
        $post_img = json_decode($postRequest->post_img);
        if (!is_array($post_img)) {
            return $this->failed('post_img格式错误');
        }
        if (count($post_img) > 9) {
            return $this->failed('最多上传9张图片');
        }
        $img_arr = [];
        foreach ($post_img as $v) {
            $save_path = $uploader->saveBase64Image($v, 'rentcloth_post', $user->id);
            if ($save_path) {
                $img_arr[] = $save_path['path'];
            } else {
                return $this->failed('图片上传失败');
            }
        }
        $rent_cloth = RentCloth::where('id', $postRequest->rent_id)->with('rentclothdetail')->first();
        $order->rent_id = $postRequest->rent_id;
        $order->shop_id = $rent_cloth->shop_id;
        $order->type = 2;
        $order->user_id = $user->id;
        $order->content = $postRequest->content;
        $order->img_url = $img_arr;

        if ($rent_cloth->rentclothdetail) {
            $order->com_id = ($rent_cloth->rentclothdetail)[0]->commodity_id;
            $order->com_attr_id = ($rent_cloth->rentclothdetail)[0]->commodity_attr_id;
            $order->brand_id = Commodity::where('id', ($rent_cloth->rentclothdetail)[0]->commodity_id)->value('brand_id');
        }
        $order->status = 1;
        $res = $order->save();
        if ($res) {
            return $this->message('申请成功');
        } else {
            return $this->failed('申请失败,请重新检查');
        }
    }
    /**
     * @title 添加晒单(店铺晒单)
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/add_rentcloth_post_line
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 晒单模块
     * @param name:shop_id type:int require:1  other: desc:店铺id
     * @param name:content type:string require:1  other: desc:评论
     * @param name:post_img type:string require:1 other: desc:图片(格式：["1","2","3"])
     *
     */
    public function add_rentcloth_post_line(Request $request, RentClothPostLineRequest $postRequest, RentClothOrder $order, ImageUploadHandler $uploader)
    {
        $user = $request->user;
        $post_img = json_decode($postRequest->post_img);
        if (!is_array($post_img)) {
            return $this->failed('post_img参数格式错误');
        }
        if (count($post_img) > 9) {
            return $this->failed('最多上传9张图片');
        }
        $shop_id = $postRequest->shop_id;
        $shop = Shop::where('id', $shop_id)->first();
        if ($user->id !== $shop->user_id) {
            return $this->failed('只能在自己的店铺中晒单');
        }
        $img_arr = [];
        foreach ($post_img as $v) {
            $save_path = $uploader->saveBase64Image($v, 'rentcloth_post_line', $user->id);
            if ($save_path) {
                $img_arr[] = $save_path['path'];
            } else {
                return $this->failed('图片上传失败');
            }
        }
        $order->type = 1;
        $order->shop_id = $shop_id;
        $order->status = 1;
        $order->user_id = $user->id;
        $order->content = $postRequest->content;
        $order->img_url = $img_arr;

        $res = $order->save();
        if ($res) {
            return $this->message('申请成功');
        } else {
            return $this->failed('申请失败,请重新检查');
        }
    }
    /**
     * @title 晒单列表(不登录的)
     * @description 接口说明 首页offset传4条
     * @author wjx
     * @url /api/rentcloth/rentcloth_post_list
     * @method POST
     *
     * @module 晒单模块
     *
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     *
     */
    public function rentcloth_post_list(Request $request, RentClothOrder $order)
    {
        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }
        if ($loadType == 'more') {
            $lists = $order->filters([['status', '=', 2], ['id', '<', $startId]])->with(['user', 'orderpraise'])->take($offset)->orderBy('id', 'desc')->get();
        } else {
            $lists = $order->filters([['status', '=', 2], ['id', '>', $startId]])->with(['user', 'orderpraise'])->take($offset)->orderBy('id', 'desc')->get();
        }

        $lists = $lists->map(function ($list) {
            $list->main_img = config('app.img_url') . ($list->img_url)[0];
            // $list->user_avatar = config('app.img_url') . $list->user->avatar;
            $list->user_avatar = $list->user->avatar;
            $list->user_nickname = $list->user->nickname;
            $list->rentcloth_order_id = $list->id;

            return $list->only(['id', 'rentcloth_order_id', 'type', 'main_img', 'user_avatar', 'user_nickname', 'hot_spot']);
        });
        if (count($lists) > 0) {
            return $this->success($lists);
        } else {
            return $this->message('暂无晒单数据');
        }

    }
    /**
     * @title 晒单列表(登录后的)
     * @description 接口说明:is_praise=1已点赞=2未点赞,首页offset传4条
     * @author wjx
     * @url /api/rentcloth/rentcloth_post_list_login
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     *
     * @module 晒单模块
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     *
     */
    public function rentcloth_post_list_login(Request $request, RentClothOrder $order)
    {
        $user = $request->user;
        if ($user) {
            $user_id = $user->id;
        } else {
            $user_id = 0;
        }
        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }
        if ($loadType == 'more') {
            $lists = $order->filters([['status', '=', 2], ['id', '<', $startId]])->with(['user', 'orderpraise'])->take($offset)->orderBy('id', 'desc')->get();
        } else {
            $lists = $order->filters([['status', '=', 2], ['id', '>', $startId]])->with(['user', 'orderpraise'])->take($offset)->orderBy('id', 'desc')->get();
        }

        $deal_line = DealLine::orderBy('id', 'desc')->first();
        $total_e = $deal_line->total_hand;
        $today_price = $deal_line->price;
        $total_price = bcdiv($total_e, $today_price, 8);
        $lists = $lists->map(function ($list) use ($user_id, $total_e, $total_price) {
            $list->main_img = config('app.img_url') . ($list->img_url)[0];
            // $list->user_avatar = config('app.img_url') . $list->user->avatar;
            $list->user_avatar = $list->user->avatar;
            $list->user_nickname = $list->user->nickname;
            $list->rentcloth_order_id = $list->id;
            $list->is_praise = $this->is_praise($user_id, $list->id);
            if ($list->hot_spot > 50) {
                $list->total_e = $total_e;
                $list->total_price = $total_price;
            } else {
                $list->total_e = -1;
                $list->total_price = -1;
            }
            return $list->only(['id', 'rentcloth_order_id', 'type', 'main_img', 'user_avatar', 'user_nickname', 'hot_spot', 'is_praise', 'total_e', 'total_price']);
        });
        if (count($lists) > 0) {
            return $this->success($lists);
        } else {
            return $this->message('暂无晒单数据');
        }

    }

    public function is_praise($user_id, $order_id)
    {
        $data = OrderPraise::where([
            ['user_id', $user_id],
            ['order_id', $order_id],
        ])->first();
        if ($data) {
            return 1;
        } else {
            return 2;
        }
    }
    /**
     * @title 我的晒单
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/rentcloth_post_detail
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 晒单模块
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     *
     * @return user_data:用户信息
     * @return lists:晒单信息
     */
    public function rentcloth_post_detail(Request $request, RentClothOrder $order)
    {
        $user = $request->user;
        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }
        if ($loadType == 'more') {
            $lists = $order->filters([['user_id', '=', $user->id], ['status', '=', 2], ['id', '<', $startId]])->with(['user', 'commodity', 'commodityattr', 'brand'])->take($offset)->orderBy('id', 'desc')->get();
        } else {
            $lists = $order->filters([['user_id', '=', $user->id], ['status', '=', 2], ['id', '>', $startId]])->with(['user', 'commodity', 'commodityattr', 'brand'])->take($offset)->orderBy('id', 'desc')->get();
        }
        $user_data = [];
        // $user_data['user_avatar'] = config('app.img_url') . $user->avatar;
        $user_data['user_avatar'] = $user->avatar;
        $user_data['user_nickname'] = $user->nickname;
        $user_data['total_browse_num'] = $order->where([['user_id', '=', $user->id], ['status', '=', 2]])->sum('browse_num');
        $user_data['total_hot_spot'] = $order->where([['user_id', '=', $user->id], ['status', '=', 2]])->sum('hot_spot');

        $lists = $lists->map(function ($list) {
            $img_arr = [];
            foreach ($list->img_url as $v) {
                $img_arr[] = config('app.img_url') . $v;
            }
            $list->img_url = $img_arr;
            $list->post_time = $list->created_at->toDateString();
            $list->brand_detail = $list->brand->name;
            $list->rentcloth_order_id = $list->id;
            return $list->only(['id', 'rentcloth_order_id', 'img_url', 'post_time', 'content', 'hot_spot', 'browse_num', 'brand_detail']);
        });
        return $this->success(compact('user_data', 'lists'));
    }

    /**
     * @title 所有晒单详情
     * @description 接口说明 type:晒单类型1线上2线下
     * @author wjx
     * @url /api/rentcloth/rentcloth_post_detail_lists
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 晒单模块
     *
     * @param name:order_id type:int require:1  other: desc:晒单id
     * @param name:type type:int require:1  other: desc:晒单类型
     */
    public function rentcloth_post_detail_lists(Request $request, RentClothOrder $order)
    {
        $user = $request->user;
        $type = $request->type;
        $order_id = $request->order_id;
        if (!$type || !$order_id) {
            return $this->failed('缺少参数');
        }
        if (!in_array($type, [1, 2])) {
            return $this->failed('参数错误');
        }
        $user_id = $user->id;
        if ($type == 2) {
            $lists = $order::with(['user', 'commodity', 'commodityattr', 'brand', 'shop'])
                ->where(['status' => 2, 'type' => 2])
                ->orderByRaw(\DB::raw("id= {$order_id} desc"))
                ->get();
            $lists_line = $order::where(['id' => $order_id])->first();
            if (!$lists_line) {
                return $this->failed('晒单不存在');
            }
            $lists_line->browse_num = $lists_line->browse_num + 1;
            $lists_line->save();
            $lists = $lists->map(function ($list) use ($user_id) {
                $img_arr = [];
                foreach ($list->img_url as $v) {
                    $img_arr[] = config('app.img_url') . $v;
                }
                $list->img_url = $img_arr;
                $list->user_avatar = $list->user->avatar;
                $list->user_nickname = $list->user->nickname;
                $list->post_time = $list->created_at->toDateString();
                $list->brand_detail = $list->brand->name;
                $list->shop_name = $list->shop->shop_name;
                $list->rentcloth_order_id = $list->id;
                $list->is_praise = $this->is_praise($user_id, $list->id);
                return $list->only(['rentcloth_order_id', 'type', 'img_url', 'user_avatar', 'user_nickname', 'post_time', 'content', 'hot_spot', 'browse_num', 'brand_detail', 'shop_name', 'is_praise']);
            });

            return $this->success($lists);
        } else {
            $lists_line = $order::with(['user', 'commodity', 'commodityattr', 'brand', 'shop'])
                ->where(['status' => 2, 'type' => 1, 'id' => $order_id])
                ->orderBy('id', 'desc')
                ->first();
            if (!$lists_line) {
                return $this->failed('晒单不存在');
            }
            $lists_line->browse_num = $lists_line->browse_num + 1;
            $lists_line->save();
            $img_arr = [];
            foreach ($lists_line->img_url as $v) {
                $img_arr[] = config('app.img_url') . $v;
            }
            $lists_line->img_url = $img_arr;
            // $lists_line->user_avatar = config('app.img_url') . $lists_line->user->avatar;
            $lists_line->user_avatar = $lists_line->user->avatar;
            $lists_line->user_nickname = $lists_line->user->nickname;
            $lists_line->post_time = $lists_line->created_at->toDateString();
            $lists_line->brand_detail = $lists_line->brand->name;
            $lists_line->shop_name = $lists_line->shop->shop_name;
            $lists_line->rentcloth_order_id = $lists_line->id;
            $lists_line->is_praise = $this->is_praise($user_id, $lists_line->id);
            $lists = $lists_line->only(['rentcloth_order_id', 'type', 'img_url', 'user_avatar', 'user_nickname', 'post_time', 'content', 'hot_spot', 'browse_num', 'brand_detail', 'shop_name', 'is_praise']);

            $shop_img = ShopCom::where('shop_id', $lists_line->shop_id)->with(['commodity'])->groupBy('commodity_id','is_buy')->limit(4)->get();
            $shop_img->transform(function ($item) {
                $item->com_img = config('app.img_url') . ($item->commodity->pictures)[0];
                return $item->only(['commodity_id', 'com_img']);
            });
            $shop_id = $lists_line->shop_id;

            return $this->success(compact('lists', 'shop_id', 'shop_img'));

        }

    }
    /**
     * @title 删除我的晒单
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/del_my_rentcloth_order
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 晒单模块
     *
     * @param name:rentcloth_order_id type:string require:1 default:1 other: desc:晒单id(例[1,2,3])
     *
     */
    public function del_my_rentcloth_order(Request $request, RentClothOrder $rent_cloth_order)
    {
        $rent_id = json_decode($request->rentcloth_order_id);
        if (!is_array($rent_id)) {
            return $this->failed('请传入数组参数');
        }

        $res = $rent_cloth_order->whereIn('id', $rent_id)->delete();
        if ($res) {
            return $this->message('删除晒单成功');
        } else {
            return $this->failed('删除订单失败');
        }
    }

    /**
     * @title 晒单点赞
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/praise_my_rentcloth_order
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 晒单模块
     * @param name:rentcloth_order_id type:int require:1 default:1 other: desc:晒单id
     * @param name:status type:int require:1 default:0 other: desc:状态（0不变1增加2减少）
     *
     */
    public function praise_my_rentcloth_order(Request $request)
    {
        $user = $request->user;
        $rent_id = $request->rentcloth_order_id;
        if (!$rent_id) {
            return $this->failed('缺少参数rentcloth_order_id');
        }
        $status = $request->status;
        $rent_cloth_order = RentClothOrder::where('id', $rent_id)->first();
        switch ($status) {
            case '1':
                $count = OrderPraise::where(['order_id' => $rent_id, 'user_id' => $user->id])->first();
                if ($count) {
                    return $this->failed('每人只能点赞一次');
                }
                $rent_cloth_order->hot_spot = $rent_cloth_order->hot_spot + 1;
                DB::beginTransaction();
                try {
                    $rent_cloth_order->save();
                    $hot_spot = $rent_cloth_order->hot_spot;
                    $reward = $rent_cloth_order->reward;
                    $user_id = $rent_cloth_order->user_id;
                    if ($hot_spot == 50 && $reward < 1) {
                        $rent_cloth_order->reward = $rent_cloth_order->reward + 1;
                        $rent_cloth_order->save();
                        Wallet::update_power($user_id, 100, 1);
                        PowerLog::add_log($user_id, 8, 100, 1);
                        event(new SendNoticeToOne($rent_cloth_order,2,5));
                    }
                    $praise = new OrderPraise();
                    $praise->order_id = $rent_id;
                    $praise->user_id = $user->id;
                    $praise->save();
                    event(new SendNoticeToOne($praise, 3, 13));                    
                    DB::commit();
                } catch (\Exception $exception) {
                    dd($exception->getMessage());
                    DB::rollBack();
                    return $this->failed('失败');
                }
                break;
            case '2':
                RentClothOrder::where('id', $rent_id)->decrement('hot_spot');
                OrderPraise::where([
                    'order_id' => $rent_id,
                    'user_id' => $user->id,
                ])->delete();
                break;

            default:
                # code...
                break;
        }

        return $this->message('成功');

    }

    /**
     * @title 晒单分享
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/rentcloth_post_detail
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 晒单模块
     *
     * @param name:order_id type:int require:1  other: desc:晒单置顶id
     */
    public function rentcloth_post_share(Request $request, RentClothOrder $order)
    {
        $user = $request->user;

        $order_id = $request->order_id;

        $lists = $order
            ->where('user_id', $user->id)
            ->with(['user', 'commodity', 'commodityattr', 'brand'])
            ->orderByRaw(\DB::raw("id= {$order_id} desc"))
            ->get();

        $lists = $lists->map(function ($list) {
            $img_arr = [];
            foreach ($list->img_url as $v) {
                $img_arr[] = config('app.img_url') . $v;
            }
            $list->img_url = $img_arr;
            // $list->user_avatar = config('app.img_url') . $list->user->avatar;
            $list->user_avatar = $list->user->avatar;
            $list->user_nickname = $list->user->nickname;
            $list->post_time = $list->created_at->toDateString();
            $list->brand_detail = $list->brand->name;
            $list->rentcloth_order_id = $list->id;
            return $list->only(['rentcloth_order_id', 'img_url', 'user_avatar', 'user_nickname', 'post_time', 'content', 'hot_spot', 'browse_num', 'brand_detail']);
        });
        return $this->success($lists);
    }
    /**
     * @title 加衣袋-付款
     * @description 接口说明
     * @author wjx
     * @url /api/rentcloth/payForBag
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 加衣劵(2.0)
     * @param name:pay_type type:int require:1 default:1 other: desc:支付方式(1余额2微信3e格码)
     * @param name:security type:string require: default: other: desc:支付密码
     */
     public function payForBag(Request $request,PayTypeRequest $payRequest)
     {
        $user = $request->user;
        $pay_type = $request->pay_type;
        if($user->robe_num == 3){
            return $this->failed('衣袋只能升级一次');
        }
        switch($pay_type){
            case 1:
                $res = $this->payBag_by_wallet($request);
                if($res !== true){
                    return $this->failed($res['message']);
                }else{
                    return $this->message('升级成功');
                }
                break;
            case 2:
                $recharge = new Recharge();
                $recharge->user_id = $user->id;
                $recharge->money = 20;
                $recharge->type = 9; //升级衣袋
                $recharge->pay_type = 2; //默认微信
                $recharge->status = 1; //待付款
                $recharge->out_trade_no = set_order_no();

                DB::beginTransaction();
                try {
                    $recharge->save();
                    DB::commit();
                    $pay = app('wechat_pay')->app([
                        'out_trade_no' => $recharge->out_trade_no,
                        // 'total_fee' => 20 * 100, // 单位是分。
                        'total_fee' => 1, // 单位是分。
                        'body' => '衣E-升级衣袋', // 订单描述
                    ]);
                    return $this->success(json_decode($pay->getContent()));
                } catch (\Exception $exception) {
                    DB::rollBack();
                    return $this->failed('出现异常，请稍后重试');
                }
                break;
            case 3:
                $res = $this->payBag_by_tmc($request);
                if($res !== true){
                    return $this->failed($res['message']);
                }else{
                    return $this->message('升级成功');
                }    
                break;
            default:
                break;
        }

     }

     public function payBag_by_wallet($request)
     {
        $user = $request->user;
        $wallet = $user->wallet;
        $amount = 20;
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }
        if ($wallet->money < $amount) {
            return ['message' => "可用余额不足"];
        }

        $user->robe_num = 3;
        $wallet->money = bcsub($wallet->money,$amount,2);
        DB::beginTransaction();
        try {
            $user->save();
            $wallet->save();
            DealLog::add_log($user->id, 0, $amount, 2, '升级衣袋(余额)');
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            
            DB::rollBack();
            return ['message'=>'出现异常，请稍后重试'];
        }
     }

     public function payBag_by_tmc($request)
     {
        $user = $request->user;
        $wallet = $user->wallet;
        $amount = 20;
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }
        $today_price = DealLine::orderBy('id', 'desc')->value('price');
        $total_e = bcdiv($amount,$today_price,8);
        
        if ($wallet->tmc < $total_e) {
            return ['message' => "可用余额不足,需要".$total_e."个e格码"];
        }
        $user->robe_num = 3;

        $wallet->money = bcsub($wallet->money,$amount,2);
        DB::beginTransaction();
        try {
            $user->save();
            $wallet->save();
            EDealLog::add_log($user->id, 0, $total_e, 2, '升级衣袋');
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['message'=>'出现异常，请稍后重试'];
        }
     }

}
